<template>
  <div class="parking-record-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>出入场信息</h2>
          <p>查看您的车辆出入记录和停车状态</p>
        </div>
      </div>
    </el-card>
    
    <!-- 统计信息 -->
    <el-row :gutter="20" v-if="stats">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="stats-card">
          <div class="stats-overview">
            <div class="stat-box total">
              <div class="stat-value">{{ stats.total }}</div>
              <div class="stat-label">总停车次数</div>
            </div>
            <div class="stat-box current">
              <div class="stat-value">{{ stats.current }}</div>
              <div class="stat-label">当前在场</div>
            </div>
            <div class="stat-box today">
              <div class="stat-value">{{ stats.today }}</div>
              <div class="stat-label">今日停车</div>
            </div>
            <div class="stat-box monthly">
              <div class="stat-value">{{ stats.monthly }}</div>
              <div class="stat-label">本月停车</div>
            </div>
            <div class="stat-box fee">
              <div class="stat-value">¥{{ stats.monthly_fee }}</div>
              <div class="stat-label">本月费用</div>
            </div>
            <div class="stat-box duration">
              <div class="stat-value">{{ formatDuration(stats.avg_duration) }}</div>
              <div class="stat-label">平均时长</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 当前在场车辆 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="current-card">
          <template #header>
            <div class="card-header">
              <span>当前在场车辆</span>
              <el-button 
                type="primary" 
                @click="fetchCurrentStatus"
                :icon="Refresh"
                circle
              ></el-button>
            </div>
          </template>
          
          <div v-loading="currentLoading">
            <div v-if="currentRecords.length > 0" class="current-list">
              <div 
                v-for="item in currentRecords" 
                :key="item.id"
                class="current-item"
              >
                <el-row :gutter="20">
                  <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="6">
                    <div class="vehicle-info">
                      <div class="plate-number">{{ item.plate_number }}</div>
                      <div class="space-info">
                        <span class="label">停车位：</span>
                        <span class="value">{{ item.space_number }}</span>
                      </div>
                      <div class="lot-info">
                        <span class="label">停车场：</span>
                        <span class="value">{{ item.parking_lot_name }}</span>
                      </div>
                    </div>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="9">
                    <div class="time-info">
                      <div class="entry-time">
                        <span class="label">入场时间：</span>
                        <span class="value">{{ formatDateTime(item.entry_time) }}</span>
                      </div>
                      <div class="duration-info">
                        <span class="label">停车时长：</span>
                        <span class="value">{{ formatDuration(item.duration.hours, item.duration.minutes) }}</span>
                      </div>
                      <div class="countdown" v-if="item.duration">
                        <el-progress 
                          :percentage="getDurationPercentage(item.duration.totalMinutes)" 
                          :color="getDurationColor(item.duration.totalMinutes)"
                          :stroke-width="8"
                          :show-text="false"
                        ></el-progress>
                      </div>
                    </div>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="9">
                    <div class="fee-info">
                      <div class="estimated-fee">
                        <span class="label">预计费用：</span>
                        <span class="value price">¥{{ item.estimated_fee.toFixed(2) }}</span>
                      </div>
                      <div class="pay-btn-container">
                        <el-button 
                          type="primary" 
                          @click="goPayment(item)"
                        >立即缴费</el-button>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
            
            <el-empty v-else description="暂无在场车辆"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 出入场记录 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="record-card">
          <template #header>
            <div class="card-header">
              <span>出入场记录</span>
              <div class="filter-actions">
                <!-- 筛选条件 -->
                <el-select 
                  v-model="filterStatus" 
                  placeholder="状态" 
                  clearable
                  @change="handleFilterChange"
                  style="width: 110px; margin-right: 10px;"
                >
                  <el-option label="全部" value="" />
                  <el-option label="进行中" :value="0" />
                  <el-option label="已完成" :value="1" />
                </el-select>
                
                <el-select 
                  v-model="filterParkingLot" 
                  placeholder="停车场" 
                  clearable
                  @change="handleFilterChange"
                  style="width: 140px; margin-right: 10px;"
                >
                  <el-option label="全部" value="" />
                  <el-option 
                    v-for="lot in parkingLots"
                    :key="lot.id"
                    :label="lot.name"
                    :value="lot.id"
                  />
                </el-select>
                
                <el-input 
                  v-model="filterPlateNumber" 
                  placeholder="车牌号" 
                  clearable
                  @clear="handleFilterChange"
                  @keyup.enter="handleFilterChange"
                  style="width: 120px; margin-right: 10px;"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                
                <el-button 
                  type="primary" 
                  @click="handleFilterChange"
                >筛选</el-button>
              </div>
            </div>
          </template>
          
          <div v-loading="recordsLoading">
            <el-table
              :data="records"
              style="width: 100%"
              :empty-text="emptyText"
              @row-click="showRecordDetail"
            >
              <el-table-column prop="plate_number" label="车牌号" width="120" />
              <el-table-column prop="space_number" label="车位" width="100" />
              <el-table-column label="入场时间" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.entry_time) }}
                </template>
              </el-table-column>
              <el-table-column label="出场时间" width="180">
                <template #default="scope">
                  {{ scope.row.exit_time ? formatDateTime(scope.row.exit_time) : '未出场' }}
                </template>
              </el-table-column>
              <el-table-column label="停车时长">
                <template #default="scope">
                  {{ formatDuration(scope.row.duration.hours, scope.row.duration.minutes) }}
                </template>
              </el-table-column>
              <el-table-column label="停车费用" width="120">
                <template #default="scope">
                  {{ scope.row.parking_fee ? '¥' + scope.row.parking_fee.toFixed(2) : '未结算' }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 0 ? 'primary' : 'success'">
                    {{ scope.row.status === 0 ? '进行中' : '已完成' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="支付状态" width="100">
                <template #default="scope">
                  <el-tag v-if="scope.row.parking_fee" :type="scope.row.is_paid ? 'success' : 'warning'">
                    {{ scope.row.is_paid ? '已支付' : '未支付' }}
                  </el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 记录详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="停车记录详情"
      width="500px"
    >
      <div v-if="selectedRecord" class="record-detail">
        <div class="detail-header">
          <div class="detail-plate">{{ selectedRecord.plate_number }}</div>
          <el-tag :type="selectedRecord.status === 0 ? 'primary' : 'success'">
            {{ selectedRecord.status === 0 ? '进行中' : '已完成' }}
          </el-tag>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">停车场：</span>
          <span class="detail-value">{{ selectedRecord.parking_lot_name }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">车位编号：</span>
          <span class="detail-value">{{ selectedRecord.space_number }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">入场时间：</span>
          <span class="detail-value">{{ formatDateTime(selectedRecord.entry_time) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">出场时间：</span>
          <span class="detail-value">{{ selectedRecord.exit_time ? formatDateTime(selectedRecord.exit_time) : '未出场' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">停车时长：</span>
          <span class="detail-value">{{ formatDuration(selectedRecord.duration.hours, selectedRecord.duration.minutes) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">停车费用：</span>
          <span class="detail-value price">{{ selectedRecord.parking_fee ? '¥' + selectedRecord.parking_fee.toFixed(2) : '未结算' }}</span>
        </div>
        <div class="detail-item" v-if="selectedRecord.parking_fee">
          <span class="detail-label">支付状态：</span>
          <el-tag :type="selectedRecord.is_paid ? 'success' : 'warning'" size="small">
            {{ selectedRecord.is_paid ? '已支付' : '未支付' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">记录编号：</span>
          <span class="detail-value">{{ selectedRecord.id }}</span>
        </div>
        
        <div class="detail-actions" v-if="selectedRecord.status === 0 || (selectedRecord.parking_fee && !selectedRecord.is_paid)">
          <el-button 
            type="primary" 
            @click="goPayment(selectedRecord)"
          >立即缴费</el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue'
import { 
  getUserParkingRecords, 
  getCurrentParkingStatus, 
  getParkingRecordDetail,
  getParkingRecordStats,
  calculateParkingDuration,
  calculateEstimatedFee
} from '@/api/parkingRecord'

// 路由
const router = useRouter()

// 停车场列表
const parkingLots = ref([
  { id: 1, name: '东区停车场' },
  { id: 2, name: '西区停车场' }
])

// 统计信息
const stats = ref(null)

// 当前在场车辆
const currentRecords = ref([])
const currentLoading = ref(false)

// 停车记录列表
const records = ref([])
const recordsLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filterStatus = ref('')
const filterParkingLot = ref('')
const filterPlateNumber = ref('')

// 详情对话框
const dialogVisible = ref(false)
const selectedRecord = ref(null)

// 空数据提示
const emptyText = computed(() => {
  if (filterStatus.value || filterParkingLot.value || filterPlateNumber.value) {
    return '没有符合条件的记录';
  }
  return '暂无停车记录';
})

// 获取统计信息
const fetchStats = async () => {
  try {
    const res = await getParkingRecordStats()
    console.log('统计信息响应:', res)
    if (res.code === 200 && res.data) {
      stats.value = {
        total: res.data.total || 0,
        current: res.data.current || 0,
        today: res.data.today || 0,
        monthly: res.data.monthly || 0,
        monthly_fee: res.data.monthlyFee || 0,
        avg_duration: res.data.avgDuration || 0
      }
    } else {
      console.warn('获取统计信息失败:', res.message)
      stats.value = null
    }
  } catch (error) {
    console.error('获取统计信息失败', error)
    stats.value = null
  }
}

// 获取当前在场车辆
const fetchCurrentStatus = async () => {
  currentLoading.value = true
  try {
    const res = await getCurrentParkingStatus()
    console.log('当前在场车辆响应:', res)
    if (res.code === 200) {
      // 处理当前在场车辆数据
      if (Array.isArray(res.data)) {
        currentRecords.value = res.data.map(record => ({
          id: record.id,
          plate_number: record.plateNumber,
          parking_lot_name: record.parkingLotName,
          space_number: record.spaceNumber,
          entry_time: record.entryTime,
          duration: calculateParkingDuration(record.entryTime, new Date().toISOString()),
          estimated_fee: calculateEstimatedFee(record.entryTime)
        }))
      } else {
        console.warn('当前在场车辆数据格式异常:', res.data)
        currentRecords.value = []
      }
    } else {
      console.error('获取当前在场车辆失败:', res.message)
      currentRecords.value = []
    }
  } catch (error) {
    console.error('获取当前车辆状态失败', error)
    ElMessage.error('获取当前车辆状态失败')
    currentRecords.value = []
  } finally {
    currentLoading.value = false
  }
}

// 获取停车记录
const fetchRecords = async () => {
  recordsLoading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: filterStatus.value || undefined,
      parkingLotId: filterParkingLot.value || undefined,
      plateNumber: filterPlateNumber.value || undefined
    }
    
    const res = await getUserParkingRecords(params)
    console.log('停车记录响应:', res)
    
    if (res.code === 200 && res.data) {
      if (Array.isArray(res.data.records)) {
        records.value = res.data.records.map(record => ({
          id: record.id,
          plate_number: record.plateNumber,
          parking_lot_name: record.parkingLotName,
          space_number: record.spaceNumber,
          entry_time: record.entryTime,
          exit_time: record.exitTime,
          parking_fee: record.parkingFee,
          is_paid: record.isPaid,
          status: record.status,
          duration: calculateParkingDuration(record.entryTime, record.exitTime || new Date().toISOString())
        }))
        total.value = res.data.total
      } else {
        console.warn('停车记录数据格式异常:', res.data)
        records.value = []
        total.value = 0
      }
    } else {
      console.error('获取停车记录失败:', res.message)
      records.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取停车记录失败', error)
    ElMessage.error('获取停车记录失败')
    records.value = []
    total.value = 0
  } finally {
    recordsLoading.value = false
  }
}

// 获取停车记录详情
const fetchRecordDetail = async (id) => {
  try {
    const res = await getParkingRecordDetail(id)
    selectedRecord.value = res.data
  } catch (error) {
    ElMessage.error('获取记录详情失败')
  }
}

// 处理筛选变更
const handleFilterChange = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRecords()
}

// 显示记录详情
const showRecordDetail = (row) => {
  selectedRecord.value = row
  dialogVisible.value = true
}

// 前往支付页面
const goPayment = (record) => {
  // 实际应用中，这里会跳转到支付页面
  router.push({
    path: '/user/payment',
    query: {
      recordId: record.id,
      recordType: 'parking'
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 格式化时长
const formatDuration = (hours, minutes) => {
  if (hours === undefined && minutes !== undefined) {
    hours = Math.floor(minutes / 60)
    minutes = minutes % 60
  }
  
  if (hours === 0 && minutes === 0) return '0分钟'
  if (hours === 0) return `${minutes}分钟`
  if (minutes === 0) return `${hours}小时`
  return `${hours}小时${minutes}分钟`
}

// 获取停车时长百分比（用于进度条）
const getDurationPercentage = (totalMinutes) => {
  // 以24小时为基准
  const max = 24 * 60
  return Math.min(100, Math.round((totalMinutes / max) * 100))
}

// 根据停车时长获取颜色
const getDurationColor = (totalMinutes) => {
  if (totalMinutes <= 60) return '#67c23a' // 1小时内
  if (totalMinutes <= 180) return '#409eff' // 3小时内
  if (totalMinutes <= 360) return '#e6a23c' // 6小时内
  return '#f56c6c' // 6小时以上
}

// 设置自动刷新（每分钟刷新一次当前车辆状态）
let refreshInterval = null

onMounted(async () => {
  await fetchStats()
  await fetchCurrentStatus()
  await fetchRecords()
  
  // 设置定时刷新
  refreshInterval = setInterval(async () => {
    if (currentRecords.value.length > 0) {
      await fetchCurrentStatus()
    }
  }, 60000) // 1分钟刷新一次
})

onBeforeUnmount(() => {
  // 清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.parking-record-container {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #3f51b5, #3949ab);
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
}

.page-title p {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

/* 统计卡片样式 */
.stats-card {
  margin-bottom: 20px;
}

.stats-overview {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.stat-box {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
  flex: 1;
  min-width: 100px;
  margin: 0 10px 10px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-box.total {
  background-color: #ecf5ff;
}

.stat-box.total .stat-value {
  color: #409eff;
}

.stat-box.current {
  background-color: #f0f9eb;
}

.stat-box.current .stat-value {
  color: #67c23a;
}

.stat-box.today {
  background-color: #fdf6ec;
}

.stat-box.today .stat-value {
  color: #e6a23c;
}

.stat-box.monthly {
  background-color: #f4f4f5;
}

.stat-box.monthly .stat-value {
  color: #909399;
}

.stat-box.fee {
  background-color: #fef0f0;
}

.stat-box.fee .stat-value {
  color: #f56c6c;
}

.stat-box.duration {
  background-color: #ecf5ff;
}

.stat-box.duration .stat-value {
  color: #409eff;
}

/* 当前车辆卡片 */
.current-card {
  margin-bottom: 20px;
}

.current-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.current-item {
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  transition: all 0.3s ease;
}

.current-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.vehicle-info {
  margin-bottom: 15px;
}

.plate-number {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.space-info, .lot-info {
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #909399;
  margin-right: 5px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.entry-time, .duration-info {
  font-size: 14px;
}

.countdown {
  margin-top: 10px;
}

.fee-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
  justify-content: center;
  height: 100%;
}

.estimated-fee {
  font-size: 14px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.pay-btn-container {
  margin-top: 10px;
}

/* 记录卡片 */
.record-card {
  margin-bottom: 20px;
}

.filter-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 详情对话框 */
.record-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-plate {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-label {
  width: 100px;
  color: #909399;
  font-size: 14px;
}

.detail-value {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media screen and (max-width: 768px) {
  .filter-actions {
    margin-top: 10px;
    width: 100%;
  }
  
  .filter-actions .el-input,
  .filter-actions .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
  
  .filter-actions .el-button {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .vehicle-info, .time-info, .fee-info {
    margin-bottom: 20px;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .detail-label {
    width: 100%;
  }
}
</style> 